package main

import (
	"encoding/json"
	"fmt"
	"log"

	"distributed-database/raft"
)

func main() {
	// 示例：从前端接收的 JSON 字符串
	receiveString := `{
        "request_id": "req-insert-1",
        "operation": "insert",
        "database": "short_video",
        "table": "user",
        "data": {
            "user_id": "123",
            "username": "alice",
            "password_hash": "hash",
            "nickname": "Alice",
            "avatar_url": "http://example.com/a.jpg",
            "gender": "male",
            "bio": "hello",
            "phone": "1234567890",
            "email": "alice@example.com",
            "register_time": "2025-10-25T12:00:00Z",
            "last_login": "2025-10-25T12:00:00Z",
            "status": "active"
        }
    }`

	// 解析前端请求
	var request struct {
		RequestID string                 `json:"request_id"`
		Operation string                 `json:"operation"`
		Database  string                 `json:"database"`
		Table     string                 `json:"table"`
		Data      map[string]interface{} `json:"data"`
		Condition map[string]interface{} `json:"condition,omitempty"`
	}

	if err := json.Unmarshal([]byte(receiveString), &request); err != nil {
		log.Fatalf("解析 JSON 失败: %v", err)
	}

	// 构建 LogValue
	logValue := raft.LogValue{
		Data:      request.Data,
		Operation: request.Operation,
		Condition: request.Condition,
		TableName: request.Table,
	}

	// 创建 ApplyMsg
	applyMsg := raft.ApplyMsg{
		Index:   1, // 通常由 Raft 分配
		Command: logValue,
	}

	// 初始化 Applyer（连接到 db0）
	applyer, err := raft.NewApplyer("../../db0.sqlite3", 0, 0)
	if err != nil {
		log.Fatalf("初始化 Applyer 失败: %v", err)
	}
	defer applyer.Close()

	// 应用日志到数据库
	if err := applyer.Apply(applyMsg); err != nil {
		log.Fatalf("应用日志失败: %v", err)
	}

	fmt.Println("✓ 数据插入成功！")

	// 示例2：更新操作
	updateString := `{
        "operation": "update",
        "table": "user",
        "data": {
            "nickname": "Alice Updated",
            "last_login": "2025-10-25T14:00:00Z"
        },
        "condition": {
            "user_id": "123"
        }
    }`

	var updateReq struct {
		Operation string                 `json:"operation"`
		Table     string                 `json:"table"`
		Data      map[string]interface{} `json:"data"`
		Condition map[string]interface{} `json:"condition"`
	}

	if err := json.Unmarshal([]byte(updateString), &updateReq); err != nil {
		log.Fatalf("解析更新 JSON 失败: %v", err)
	}

	updateLogValue := raft.LogValue{
		Data:      updateReq.Data,
		Operation: updateReq.Operation,
		Condition: updateReq.Condition,
		TableName: updateReq.Table,
	}

	updateMsg := raft.ApplyMsg{
		Index:   2,
		Command: updateLogValue,
	}

	if err := applyer.Apply(updateMsg); err != nil {
		log.Fatalf("应用更新日志失败: %v", err)
	}

	fmt.Println("✓ 数据更新成功！")

	// 示例3：删除操作
	deleteString := `{
        "operation": "delete",
        "table": "user",
        "condition": {
            "user_id": "123"
        }
    }`

	var deleteReq struct {
		Operation string                 `json:"operation"`
		Table     string                 `json:"table"`
		Condition map[string]interface{} `json:"condition"`
	}

	if err := json.Unmarshal([]byte(deleteString), &deleteReq); err != nil {
		log.Fatalf("解析删除 JSON 失败: %v", err)
	}

	deleteLogValue := raft.LogValue{
		Operation: deleteReq.Operation,
		Condition: deleteReq.Condition,
		TableName: deleteReq.Table,
	}

	deleteMsg := raft.ApplyMsg{
		Index:   3,
		Command: deleteLogValue,
	}

	if err := applyer.Apply(deleteMsg); err != nil {
		log.Fatalf("应用删除日志失败: %v", err)
	}

	fmt.Println("✓ 数据删除成功！")
}
